﻿//--------------------------------------------------------------------------------------------------------------
// <copyright file="CSPMembershipUpdateWUC.cs" company="Microsoft Corporation" date="01/01/2008">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//--------------------------------------------------------------------------------------------------------------


using System;
using System.Collections;
using System.Collections.Specialized;
using System.Reflection;
using System.Resources;
using System.Runtime.InteropServices;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Serialization;

using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint.WebPartPages;


namespace CSP.WebParts.UserControls
{

    /// <summary>
    /// Allows the citizens to update his/her profile
    /// </summary> 
    public class CSPMembershipUpdateWUC :  CSPBaseWUC 
    {
       
        #region Members       
        protected Label errorLabel;
        protected HyperLink redirectLink;      
        private string userNotAuthenticatedMessage = WebPartConstants.CSPUserNotAuthenticated;
        private string invalidDataMessage = WebPartConstants.CSPInvalidDataFromCRM;
        private string administratorMessage = WebPartConstants.CSPLoggedAsAdministrator;                   
        protected Label UpdateUsername2;
        protected TextBox tbFirstName;
        protected TextBox tbLastName;
        protected TextBox tbEmail;
        protected TextBox tbAddress;
        protected TextBox tbCity;
        protected TextBox tbPostalCode;
        protected TextBox tbPhone;
        protected TextBox tbChildren;
        protected TextBox tbElderlyRelatives;
        protected Image photo;
        protected FileUpload fuNewPicture;
        protected Button UpdateSubmit;
        protected Panel pnlForm;
        protected Panel pnlResult;
        protected Label UpdateChildren;
        protected Label UpdateElderlyRelatives;
        protected Label UpdatePostalCode; 

        #endregion

        #region properties
        public string NoImageUrl { get; set; }
        public string CitizenImagesGalleryURL { get; set; }
        #endregion

        #region PageEvents
        /// <summary>
        /// Fired on page load
        /// </summary> 
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    if (!Page.IsPostBack)
                    {
                        this.LoadLabels();
                        this.LoadData();
                    }

                });
            }          
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPMembershipUpdateLoadErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
        }

        /// <summary>
        /// Fired on page create child controls
        /// </summary> 
        protected override void CreateChildControls()
        {
            base.CreateChildControls();

            try
            {
                AddHipControls();

                UpdateSubmit.CausesValidation = true;
                UpdateSubmit.ValidationGroup = this.ID;
                UpdateSubmit.Click += new EventHandler(UpdateSubmit_Click);
            }           
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPMembershipUpdateCreateChildControlsErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
        }
        #endregion


        #region Methods
        /// <summary>
        /// Gets the labels data
        /// </summary>     
        protected void LoadLabels()
        {
            try
            {
                base.LoadLabels(this.pnlForm);
            }
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPGenericErrorMessage), this.GetType().Name, ex);
                throw ex;
            }

        }

        /// <summary>
        /// Gets the citizen data
        /// </summary>          
        private void LoadData()
        {
            CSP.MembershipInterface.MembershipServiceClient client = null;

            try
            {              
                string username = Context.User.Identity.Name;

                client = new CSP.MembershipInterface.MembershipServiceClient();

                CSP.MembershipInterface.ObjectModel.Citizen citizen = client.GetCitizenByUsername(username);

                if (citizen == null)
                    throw new Exception(WebPartConstants.CSPMembershipUpdateCitizenNotFoundErrorMessage);


                this.UpdateUsername2.Text = username;
                this.tbFirstName.Text = citizen.FirstName;
                this.tbLastName.Text = citizen.LastName;
                this.tbEmail.Text = citizen.EmailAddress;
                this.tbAddress.Text = citizen.Address;
                this.tbCity.Text = citizen.City;
                this.tbPostalCode.Text = citizen.PostalCode;
                this.tbPhone.Text = citizen.Phone;
                this.tbChildren.Text = citizen.Children;
                this.tbElderlyRelatives.Text = citizen.ElderlyRelatives;


                if (!String.IsNullOrEmpty(citizen.PhotoUrl))
                {
                    this.photo.ImageUrl = citizen.PhotoUrl;
                }
                else
                {
                    this.photo.ImageUrl = this.NoImageUrl;
                }
            }
            catch (CSP.Core.CSPException cspex)
            {
                throw cspex;
            }
            catch (Exception ex)
            {
                this.LogMessage(this.LoadResource(WebPartConstants.CSPGenericErrorMessage), this.GetType().Name, ex);
                throw ex;
            }
            finally
            {
                if (client != null && client.State != System.ServiceModel.CommunicationState.Closed)
                    client.Close();
            }
        }
        #endregion
            

        #region ControlEvents
        /// <summary>
        /// Updates the citizen data. Fired when update button is clicked
        /// </summary>   
        protected void UpdateSubmit_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                CSP.MembershipInterface.MembershipServiceClient client = null;
                try
                {                   
                    string username = Context.User.Identity.Name;

                    client = new CSP.MembershipInterface.MembershipServiceClient();

                    CSP.MembershipInterface.ObjectModel.CitizenRequest citizenRequest = new CSP.MembershipInterface.ObjectModel.CitizenRequest();
                    
                    citizenRequest.Address = tbAddress.Text;
                    citizenRequest.Children = tbChildren.Text;
                    citizenRequest.City = tbCity.Text;
                    citizenRequest.DefaultGroup = WebPartConstants.CSPCitizensDefaultGroup;
                    citizenRequest.DisplayName = tbFirstName.Text + " " + tbLastName.Text;
                    citizenRequest.ElderlyRelatives = tbElderlyRelatives.Text;
                    citizenRequest.EmailAddress = tbEmail.Text;
                    citizenRequest.FirstName = tbFirstName.Text;
                    citizenRequest.LastName = tbLastName.Text;
                    citizenRequest.Phone = tbPhone.Text;
                    citizenRequest.PostalCode = tbPostalCode.Text;
                    citizenRequest.RequestType = CSP.MembershipInterface.ObjectModel.CitizenRequestType.Update;
                    citizenRequest.Username = username;
                
                    citizenRequest.PhotoUrl = citizenRequest.PhotoUrl;
                    if (fuNewPicture.HasFile)
                    {
                        Random r = new Random();
                        string extension = System.IO.Path.GetExtension(fuNewPicture.FileName).ToUpper();
                        string filename = System.IO.Path.GetFileName(fuNewPicture.FileName);



                        string newUrl = Server.HtmlEncode(string.Format("{0}/{1}/{2}/{3}", SPContext.Current.Site.Url.ToString(), LoadResource("CSP_mycity_name"), "CitizenImages", username + "_" + r.Next(10000).ToString() + "_" + filename));
                        byte[] fileBytes = fuNewPicture.FileBytes;

                        if (extension == ".GIF" || extension == ".JPG" || extension == ".PNG" && fileBytes.Length < 500000)
                        {
                            // Upload the image to the sharepoint citizen image library
                            SPSecurity.RunWithElevatedPrivileges(delegate()
                            {
                                SPSite site = SPContext.Current.Site;
                                SPWeb authenticatedMyCity = site.RootWeb.Webs[LoadResource("CSP_mycity_name")];
                                authenticatedMyCity.AllowUnsafeUpdates = true;
                                SPFolder imageLibraryFolder = authenticatedMyCity.GetFolder("CitizenImages");
                                
                                imageLibraryFolder.Files.Add(newUrl, fileBytes);
                            });

                            citizenRequest.PhotoUrl = newUrl;
                        }
                    }



                    if (!Core.FormValidator.IsEmail(this.tbEmail.Text))
                    {
                        this.LogMessage(LoadResource(WebPartConstants.CSPErrorInvalidEmailFormat), this.GetType().Name);
                        WrapperWebPart.AddError(LoadResource(WebPartConstants.CSPErrorInvalidEmailFormat));
                    }
                    if (!Core.FormValidator.IsNumber(this.tbChildren.Text))
                    {
                        this.LogMessage(string.Format(LoadResource(WebPartConstants.CSPErrorMustBeNumber), LoadLabelName(this.UpdateChildren.Text)), this.GetType().Name);
                        WrapperWebPart.AddError(string.Format(LoadResource(WebPartConstants.CSPErrorMustBeNumber), LoadLabelName(this.UpdateChildren.Text)));
                    }
                    if (!Core.FormValidator.IsNumber(this.tbElderlyRelatives.Text))
                    {
                        this.LogMessage(string.Format(LoadResource(WebPartConstants.CSPErrorMustBeNumber), LoadLabelName(this.UpdateElderlyRelatives.Text)), this.GetType().Name);
                        WrapperWebPart.AddError(string.Format(LoadResource(WebPartConstants.CSPErrorMustBeNumber), LoadLabelName(this.UpdateElderlyRelatives.Text)));
                    }
                    


                    if (!WrapperWebPart.AnyError())
                    {
                        client.AddCitizenRequest(citizenRequest);
                        this.LogMessage(LoadResource(WebPartConstants.CSPRegisterSuccessMessage), this.GetType().Name);
                        WrapperWebPart.AddError(LoadResource((WebPartConstants.CSPUpdateSuccessMessage)));
                    }
                    else {
                        WrapperWebPart.AddError(string.Format(LoadResource(WebPartConstants.CSPBack)));                                        
                  
                    }
                }

                catch (CSP.Core.CSPException cspex)
                {
                    throw cspex;
                }
                catch (Exception ex)
                {
                    this.LogMessage(this.LoadResource(WebPartConstants.CSPCitizenProfileLoadErrorMessage), this.GetType().Name, ex);
                    throw ex;
                }
                finally
                {
                    if (client != null && client.State != System.ServiceModel.CommunicationState.Closed)
                        client.Close();
                }                     
            }
        }
        private string LoadLabelName(string lbl)
        {

            return lbl.Replace(":", ""); ;
        }
        #endregion
    }
}
